package org.example.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.erp.domain.*;
import org.example.erp.service.SysRoleService;
import org.example.erp.service.SysUserService;
import org.example.erp.service.impl.SysRoleMenuServiceImpl;
import org.example.erp.service.impl.SysRoleServiceImpl;
import org.example.erp.service.impl.SysUserRoleServiceImpl;
import org.example.erp.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RequestMapping("/api")
@RestController
public class RoleController {

    @Autowired
    SysRoleServiceImpl sysRoleService;//角色表

    @Autowired
    SysRoleMenuServiceImpl sysRoleMenuService;//角色菜单表

    @Autowired
    SysUserServiceImpl sysUserService;//用户表

    @Autowired
    SysUserRoleServiceImpl sysUserRoleService;//用户角色表

    @GetMapping("/roleManagement/find")//查询角色列表（分页，带参）
    public DataResult findRoles(
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String roleName,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String roleKey,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startCreateTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endCreateTime
    ) {
        LambdaQueryWrapper<SysRole> postMapper = new LambdaQueryWrapper<>();
        IPage<SysRole> page = new Page<>(currentPage, pageSize);
        //链式调用,前面是表达式，判断条件是否成立
        postMapper.like(!"".equals(roleName) && roleName != null, SysRole::getRoleName, roleName)
                .like(!"".equals(roleKey) && roleKey != null, SysRole::getRoleKey, roleKey)
                .eq(!"".equals(status) && status != null, SysRole::getStatus, status)
                .ge(startCreateTime != null, SysRole::getCreateTime, startCreateTime)
                .le(endCreateTime != null, SysRole::getCreateTime, endCreateTime)
                .orderByAsc(SysRole::getRoleSort); // 按 roleSort 升序排序
        IPage<SysRole> pageResult = sysRoleService.page(page, postMapper);
        return DataResult.success(pageResult);
    }

    @PutMapping("/roleManagement/updateRoleStatus")//修改角色状态
    public DataResult updateStatus(
            @RequestBody SysRole sysRole
    ) {
        Integer roleId = sysRole.getRoleId();
        String status = sysRole.getStatus();
        sysRoleService.updateRoleStatus(roleId, status);
        return DataResult.success();
    }

    @PostMapping("/roleManagement/insert")
    public DataResult insert(@RequestBody GrantVo vo) {//添加角色，并且根据角色编号，保存当前角色的权限信息
        vo.getSysRole().setCreateTime(new Date());
        boolean save = sysRoleService.save(vo.getSysRole());
        if (!save) {
            return DataResult.error("角色保存失败");
        }
        SysRole sysRole = vo.getSysRole();
        Integer roleId = sysRole.getRoleId();
        List<Integer> menuIds = vo.getMenuIds();
        System.out.println("用户Id：" + roleId + "菜单Id:[" + menuIds + "]");
        int i = sysRoleMenuService.saveGrant(roleId, vo.getMenuIds());
        return DataResult.success();
    }

    @PutMapping("/roleManagement/update")
    public DataResult update(@RequestBody GrantVo vo) {//修改用户
        vo.getSysRole().setUpdateTime(new Date());
        System.out.println("要修改的角色信息：" + vo.getSysRole());
        boolean update = sysRoleService.updateById(vo.getSysRole());
        if (!update) {
            return DataResult.error("角色修改失败");
        }
        SysRole sysRole = vo.getSysRole();
        Integer roleId = sysRole.getRoleId();
        List<Integer> menuIds = vo.getMenuIds();
        sysRoleMenuService.saveGrant(roleId, menuIds);
        return DataResult.success();
    }

    @GetMapping("/roleManagement/selectUsers")
    public DataResult findSelectUser(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "2") Integer sizePage,
            @RequestParam Integer roleId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phone
    ){//查询用户角色表。（查询已经授权了角色的用户，带参带分页）
        IPage<SysUser> page = new Page<>(currentPage,sizePage);
        IPage<SysUser> selectUser = sysUserService.findSelectUser(page, roleId, username, phone);
        return DataResult.success(selectUser);
    }

    @DeleteMapping("/roleManagement/delete")
    public DataResult delete(@RequestBody List<Long> roleId){//删除角色
        sysRoleService.removeBatchByIds(roleId);
        return DataResult.success();
    }

    @PostMapping("/roleManagement/findRoleAssignUsers")//查询已分配的角色
    public DataResult findRoleAssignUsers(@RequestBody List<Integer> ids){
        int roleAssignUsers = sysUserRoleService.findRoleAssignUsers(ids);
        return DataResult.success(roleAssignUsers);
    }

}
